package com.zkjd.lingdong.service.executor

import android.car.Car
import android.car.media.CarAudioManager
import android.content.Context
import android.media.AudioManager
import android.os.SystemClock
import android.view.KeyEvent
import com.zkjd.lingdong.model.ButtonFunction
import com.zkjd.lingdong.model.ButtonType
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton


private const val TAG = "NewFunctionExecutor"
/**
 * 媒体功能执行器
 * 负责处理媒体控制相关功能，如音量调节、切换音乐等
 */
@Singleton
class NewFunctionExecutor @Inject constructor(
    private val context: Context
) {
    private val audioManager: AudioManager by lazy {
        context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
    }


    /**
     * 执行媒体相关功能
     * @param function 要执行的功能
     * @param buttonType 触发的按键类型，用于处理旋转功能
     */
    suspend fun executeNewFunction(function: ButtonFunction, buttonType: ButtonType = ButtonType.SHORT_PRESS) {
        Timber.tag(TAG)
            .d("执行媒体功能: ${function.name}, 代码: ${function.actionCode}, 按键类型: $buttonType")

        val array=function.useType.toString().split("")
        // 处理旋转类功能
        if (array[1].toInt()==2 &&
           (buttonType == ButtonType.LEFT_ROTATE || buttonType == ButtonType.RIGHT_ROTATE)) {
            when (function.actionCode) {
                "MEDIA_VOLUME_CONTROL" -> {
                    // 音量控制
                    if (buttonType == ButtonType.RIGHT_ROTATE) {
                        volumeUp() // 顺时针旋转，增大音量
                    } else {
                        volumeDown() // 逆时针旋转，减小音量
                    }
                    return
                }
                "MEDIA_MUSIC_SWITCH" -> {
                    // 音乐切换
                    if (buttonType == ButtonType.RIGHT_ROTATE) {
                        nextTrack() // 顺时针旋转，下一首
                    } else {
                        previousTrack() // 逆时针旋转，上一首
                    }
                    return
                }
            }
        }

        // 处理普通功能
        when (function.actionCode) {
            "MEDIA_VOLUME_UP" -> volumeUp()
            "MEDIA_VOLUME_DOWN" -> volumeDown()
            "MEDIA_NEXT_TRACK" -> nextTrack()
            "MEDIA_PREVIOUS_TRACK" -> previousTrack()
            "MEDIA_PLAY_PAUSE" -> playPause()
            "MEDIA_MUTE_TOGGLE" -> toggleMute()

            else -> {
                Timber.tag(TAG).w("未知媒体功能代码: ${function.actionCode}")
            }
        }
    }

    /**
     * 增加音量
     */
    fun volumeUp() {
        Timber.tag(TAG).w("增加音量")
        try {
            // 获取当前音量
            val currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
            // 获取最大音量
            val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)

            if (currentVolume < maxVolume) {
                // 使用AudioManager增加音量
                audioManager.adjustStreamVolume(
                    AudioManager.STREAM_MUSIC,
                    AudioManager.ADJUST_RAISE,
                    0  // 不显示UI
                )
                Timber.tag(TAG).w("音量已增加：${currentVolume + 1}/$maxVolume")
            } else {
                Timber.tag(TAG).w("音量已达最大值：$maxVolume")
            }
        } catch (e: Exception) {
            Timber.tag(TAG).e(e, "增加音量失败: ${e.message}")
        }
    }

    /**
     * 降低音量
     */
    fun volumeDown() {
        Timber.tag(TAG).w("降低音量")
        try {
            // 获取当前音量
            val currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
            // 获取最大音量（用于日志）
            val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)

            if (currentVolume > 0) {
                // 使用AudioManager降低音量
                audioManager.adjustStreamVolume(
                    AudioManager.STREAM_MUSIC,
                    AudioManager.ADJUST_LOWER,
                    0  // 不显示UI
                )
                Timber.tag(TAG).w("音量已降低：${currentVolume - 1}/$maxVolume")
            } else {
                Timber.tag(TAG).w("音量已达最小值：0")
            }
        } catch (e: Exception) {
            Timber.tag(TAG).e(e, "降低音量失败: ${e.message}")
        }
    }

    /**
     * 播放下一首
     */
    fun nextTrack() {
        Timber.tag(TAG).w("播放下一首")
        try {
            // 使用mediaButton模拟按下下一首按钮
            val keyEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT)
            audioManager.dispatchMediaKeyEvent(keyEvent)

            // 确保按键释放
            val keyEventUp = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_NEXT)
            audioManager.dispatchMediaKeyEvent(keyEventUp)

//            sendMediaKeyEvent(KeyEvent.KEYCODE_MEDIA_NEXT)
            Timber.tag(TAG).w("已发送播放下一首命令")
        } catch (e: Exception) {
            Timber.tag(TAG).e(e, "播放下一首失败: ${e.message}")
        }
    }

    /**
     * 播放上一首
     */
    fun previousTrack() {
        Timber.tag(TAG).w("播放上一首")
        try {
            // 使用mediaButton模拟按下上一首按钮
            val keyEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS)
            audioManager.dispatchMediaKeyEvent(keyEvent)

            // 确保按键释放
            val keyEventUp = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PREVIOUS)
            audioManager.dispatchMediaKeyEvent(keyEventUp)


//            sendMediaKeyEvent(KeyEvent.KEYCODE_MEDIA_PREVIOUS)
            Timber.tag(TAG).w("已发送播放上一首命令")
        } catch (e: Exception) {
            Timber.tag(TAG).e(e, "播放上一首失败: ${e.message}")
        }
    }

    /**
     * 播放/暂停
     */
    fun playPause() {
        Timber.tag(TAG).w("播放/暂停")
        try {

            // 使用mediaButton模拟按下播放/暂停按钮

//            val keyEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE)
//
//            audioManager.dispatchMediaKeyEvent(keyEvent)
//
//            // 确保按键释放
//            val keyEventUp = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE)
//            audioManager.dispatchMediaKeyEvent(keyEventUp)

           sendMediaKeyEvent(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE)


            Timber.tag(TAG).w("已发送播放/暂停命令")
        } catch (e: Exception) {
            Timber.tag(TAG).e(e, "播放/暂停失败: ${e.message}")
        }
    }

    private fun sendMediaKeyEvent(keyCode: Int) {
        // 模拟按下事件

        val now = SystemClock.uptimeMillis()
        val keyEventDown = KeyEvent(now, now, KeyEvent.ACTION_DOWN, keyCode, 0)
        val keyEventUp = KeyEvent(now, now, KeyEvent.ACTION_UP, keyCode, 0)

        try {

                val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
                audioManager.dispatchMediaKeyEvent(keyEventDown)
                audioManager.dispatchMediaKeyEvent(keyEventUp)

        } catch (e: Exception) {
            Timber.tag(TAG).e(e, "发送媒体按键事件失败: ${e.message}")
        }
    }


    /**
     * 静音/取消静音
     */
    fun toggleMute() {
        Timber.tag(TAG).w("静音/取消静音")
        try {


            // 获取当前静音状态
            val isMuted = audioManager.isStreamMute(AudioManager.STREAM_MUSIC)

            // 切换静音状态
            if (isMuted) {
                audioManager.adjustStreamVolume(
                    AudioManager.STREAM_MUSIC,
                    AudioManager.ADJUST_UNMUTE,
                    0  // 不显示UI
                )
                Timber.tag(TAG).w("已取消静音")
            } else {
                audioManager.adjustStreamVolume(
                    AudioManager.STREAM_MUSIC,
                    AudioManager.ADJUST_MUTE,
                    0  // 不显示UI
                )
                Timber.tag(TAG).w("已设置静音")
            }
        } catch (e: Exception) {
            Timber.tag(TAG).e(e, "静音/取消静音失败: ${e.message}")
        }
    }
}